package it.unicam;

import hermesV2.PlaceAddress;
import hermesV2.services.P2P_ServiceAgent;

import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class HermesLog extends Activity{
	private TextView txtLogP2P ;
	private ListView listPeer;
	public static HermesLog instance;
	final  Handler logHandler = new Handler();
	final Handler  listHandler = new Handler();
	private static String[] peers_id;
	
	
	final  Runnable logUpdateResults = new Runnable() {
        public void run() {
        	writeLog();
        }
    };
    final  Runnable listUpdateResults = new Runnable() {
        public void run() {
        	writeList();
        }
    };
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instance = this;
        setContentView(R.layout.log);        	
         txtLogP2P=(TextView)findViewById(R.id.textLog);
         listPeer=(ListView)findViewById(R.id.lstViewPeer);
         Button btnClear = (Button) findViewById(R.id.btnDelete);
         writeLog();
         
         btnClear.setOnClickListener(new Button.OnClickListener() {
     		@Override
     		public void onClick(final View v) {
     			txtLogP2P.setText("");
     			P2P_ServiceAgent.clearLog();
     		}
     	 });
         
         
         
         String peer[]={"","",""};
         ArrayAdapter<String> styleList = new ArrayAdapter<String>(this, R.layout.list_item,peer);
         listPeer.setAdapter(styleList);
         listPeer.setItemsCanFocus(true);  
         if (peers_id != null) 
		   {
        	 rfe(peers_id);
		   }
    }
	
	
     		
	 public  void refreshLog() {
		 if (txtLogP2P==null) {return;}
	        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
	        Thread t = new Thread() {
	            public void run() {
	                logHandler.post(logUpdateResults);
	            }
	        };
	        t.start();
	 }
	 
	 public  void refreshList(Vector<PlaceAddress> peers) {
		 peers_id = new String [peers.size()];
		 for (int i=0; i<peers.size(); i++)
		 {
			peers_id[i] = peers.get(i).toString();
		 }
		 rfe(peers_id);
	 }
	
	
	 private void rfe(String [] peers_id)
	 {
		 if (listPeer==null) {return;}
	        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
	        Thread t = new Thread() {
	            public void run() {
	                listHandler.post(listUpdateResults);
	            }
	        };
	        t.start();
	 }
	 
	 
	 private  void writeLog(){
		if (txtLogP2P==null) {return;}
		txtLogP2P.setText(P2P_ServiceAgent.getLog());
	 }
	 
	 private  void writeList(){
			if (listPeer==null) {return;}
			listPeer.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, peers_id));
		 }
	
	 
	 

	 
}
	
	

